<template>
	<view class="pb-safe-area">
		<view class="tab p-4">
			<view class="flex-1 bg-white rounded-4">
				<view class="flex">
					<text class="flex-1 py-4 text-center h9" @tap="navClick(item)"
						:class="item.scene == search.state ? 'text-primary font-weight-600' : ''"
						v-for="(item, index) in navList" :key="index" :id="item.scene">{{ item.name }}</text>
				</view>
			</view>
		</view>
		<view class="p-4 flex flex-column grid-gap-4" v-if="list.length > 0 || loading === 'loading'">
			<x-coupon-item v-for="(item, index) in list" :key="index" :item="item">
				<template #action>
					<template v-if="item.state === 0">
						<button class="btn-success btn-round shadow text-nowrap" size="mini"
							@tap="$page.switch('/pages/index/index')">去使用</button>
					</template>
					<template v-else-if="item.state === 1">
						<button class="btn-placeholder btn-round shadow text-nowrap" size="mini">已使用</button>
					</template>
					<template v-else-if="item.state === 99">
						<button class="btn-danger btn-round shadow text-nowrap" size="mini">已过期</button>
					</template>
				</template>
			</x-coupon-item>
			<x-more :status="loading" @load="getList()"></x-more>
		</view>
		<view class="vh-50 flex flex-center" v-else>
			<x-empty type="order" text="暂无优惠券"></x-empty>
		</view>
	</view>
</template>

<script setup lang="ts">
import { ref, nextTick } from 'vue';
import { $api, $message, $page } from '@/utils';
import { onLoad, onReachBottom } from '@dcloudio/uni-app';
const loading = ref('loadmore');
const list = ref([]);
const navList = ref([
	{ name: '未使用', scene: 'unused' },
	{ name: '已使用', scene: 'used' },
	{ name: '已过期', scene: 'expired' },
]);
const search = ref({
	page: 1,
	state: 'unused',
});
const navClick = (e) => {
	search.value.state = e.scene;
	list.value = [];
	search.value.page = 1;
	loading.value = 'loadmore';
	getList();
}
const getList = () => {
	if (loading.value === 'loading' || loading.value === 'nomore') return;
	loading.value = 'loading';
	$api.Coupon.list(search.value).then(data => {
		list.value = [...list.value, ...data.data];
		search.value.page++;
		if (data.current_page >= data.last_page) {
			nextTick(() => {
				loading.value = 'nomore';
			})
		}
	}).catch(() => {
		nextTick(() => {
			loading.value = 'nomore';
		})
	}).finally(() => {
		if (loading.value === 'loading') {
			loading.value = 'loadmore';
		}
	})
}
onLoad(() => {
	getList();
})
onReachBottom(() => {
	getList();
})
</script>

<style lang="scss" scoped>
.tab {
	position: sticky;
	/* #ifdef H5 */
	top: var(--window-top);
	/* #endif */
	/* #ifndef H5 */
	top: 0;
	/* #endif */
	z-index: 999;
	background-color: $uni-bg-color-grey;

	&-body {
		height: 50px;
		line-height: 50px;
		display: inline-flex;
		justify-content: center;
		align-items: center;
		gap: 20px;

		&-item {
			padding: 0 10px;
			word-break: nowrap;
			white-space: nowrap;
		}
	}
}
</style>
